package com.sophie.chapter3;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.TopicPartition;

import java.time.Duration;
import java.util.Arrays;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicBoolean;

public class KafkaConsumerAnalysis {

    private static final String brokerList = "120.79.216.84:8196";

    private static final String topic = "heima";

    private static final String groupId = "group.demo";

    public static final AtomicBoolean isRunning = new AtomicBoolean(true);

    public static Properties initConfig() {
        Properties properties = new Properties();
        // 与kafkaProducer中设置保值一致
        // 设置KEY反序列化器
        properties.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        // 设置值反序列化器
        properties.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        // 设置集群地址
        properties.put("bootstrap.servers", brokerList);
        // 默认为空，指定消费组
        properties.put("group.id", groupId);
        // 指定kafkaConsumer对应的客户端id，默认为空
        properties.put("client.id", "consumer.client.id.demo");
        // 指定小分支拦截器
        properties.put(ConsumerConfig.INTERCEPTOR_CLASSES_CONFIG, ConsumerInterceptorTTL.class.getName());

        return properties;
    }


    public static void main(String[] args) {
        Properties properties = initConfig();
        KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(properties);
        consumer.subscribe(Arrays.asList(topic));
        // 正则订阅主题
        // consumer.subscribe(Pattern.compile("heima"));
        // 指定订阅的分区
        consumer.assign(Arrays.asList(new TopicPartition("heima", 0)));
        try {
            while (isRunning.get()) {
                ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(1000));
                for (ConsumerRecord<String, String> record : records) {
                    System.out.println("topic=" + record.topic() + ",partition=" + record.partition() + "offset=" + record.offset());
                    System.out.println("key=" + record.key() + ",value=" + record.value());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            consumer.close();
        }
    }
}
